package nix.hibernate;

import nix.utils.HibernateUtils;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

public class DemoCache {

	/**
	 * 一级缓存
	 */
	@Test
	public void fun1() {
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();

		User u1 = (User) session.get(User.class, 1);
		User u2 = (User) session.get(User.class, 1);
		User u3 = (User) session.get(User.class, 1);
		User u4 = (User) session.get(User.class, 1);
		User u5 = (User) session.get(User.class, 1);
		// 只输出一次select语句
		System.out.println(u1 == u5);// true
		
		tx.commit();
		session.close();
	}
	
	@Test
	public void fun2() {
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();

		User u = (User) session.get(User.class, 1);
		u.setName("赵六");
		u.setName("王五");
		// 原始数据为“王五”，以上两次set不输出（执行）update语句
		tx.commit();
		session.close();
	}
	
	@Test
	public void fun3() {
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();

		User u1 = new User();
		u1.setId(99);
		session.update(u1);
		User u2 = (User) session.get(User.class, 99); 
		// commit之前不输出（执行）任何sql语句
		tx.commit();
		session.close();
	}
}
